<?php


namespace App\Console\Commands;

use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Workerman\Worker;


class WorkermanCommand extends Command
{

    protected $signature = 'workman {action} {--daemon}';

    protected $description = 'Start a Workerman server.';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        global $argv;

        if (!in_array($action = $this->argument('action'), ['start', 'stop', 'restart'])) {
            $this->error('Error Arguments');
            exit;
        }

        $argv[0] = 'workman';
        $argv[1] = $action;
        $argv[2] = $this->option('daemon') ? '-d' : '';

        $this->start();
    }

    private function start()
    {
        $this->startGateWay();
        $this->startBusinessWorker();
        $this->startRegister();
        Worker::runAll();
    }

    private function startBusinessWorker()
    {
        $worker                  = new BusinessWorker();
        $worker->name            = 'BusinessWorker_dinner';
        $worker->count           = 1;
        $worker->registerAddress = '0.0.0.0:51236';
        $worker->eventHandler    = \App\WorkerMan\Events::class;
    }

    private function startGateWay()
    {
        Log::info('start getway');
        $gateway = new Gateway("websocket://0.0.0.0:52346");
        $gateway->name                 = 'Gateway_dinner';
        $gateway->count                = 1;
        $gateway->lanIp                = '0.0.0.0';
        $gateway->startPort            = 2300;
        $gateway->pingInterval         = 30;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = '{"type":"@heart@"}';
        $gateway->registerAddress      = '0.0.0.0:51236';
    }

    private function startRegister()
    {
        new Register('text://0.0.0.0:51236');
    }
}